import Foundation
import Flutter
import UIKit
import SystemConfiguration
import FinAuthLiveV5Detect

/**
 * iOS端NativeBridge封装类
 * 负责处理Flutter和iOS原生代码之间的通信
 */
@objc class NativeBridge: NSObject {
    
    // MARK: - Properties
    
    /// 方法通道
    private var methodChannel: FlutterMethodChannel?
    
    /// 事件通道
    private var eventChannel: FlutterEventChannel?
    
    /// 事件发送器
    private var eventSink: FlutterEventSink?
    
    // MARK: - Singleton
    
    static let shared = NativeBridge()
    
    private var controller: UIViewController?
    
    private override init() {
        super.init()
    }
    
    // MARK: - Initialization
    
    /// 初始化NativeBridge
    /// - Parameter messenger: Flutter二进制消息发送器
    func initialize(controller: FlutterViewController) {
        self.controller = controller
        // 设置方法通道
        methodChannel = FlutterMethodChannel(name: "native_bridge", binaryMessenger: controller.binaryMessenger)
        methodChannel?.setMethodCallHandler { [weak self] (call, result) in
            self?.handleMethodCall(call, result: result)
        }
        
        // 设置事件通道
        eventChannel = FlutterEventChannel(name: "native_events", binaryMessenger: controller.binaryMessenger)
        eventChannel?.setStreamHandler(self)
        
        print("iOS NativeBridge initialized successfully")
    }
    
    // MARK: - Method Call Handling
    
    /// 处理来自Flutter的方法调用
    private func handleMethodCall(_ call: FlutterMethodCall, result: @escaping FlutterResult) {
        switch call.method {
        case "showToast":
            let message = (call.arguments as? [String: Any])?["message"] as? String ?? ""
            let success = showToast(message: message)
            result(success)
            break
        case "faceAuth":
            guard let params = call.arguments as? [String: String] else {
                result(false)
                return
            }
            guard let token = params["token"] else {
                result(false)
                return
            }
            faceAuth(token: token) { success in
                result(success)
            }
            break
        default:
            result(FlutterMethodNotImplemented)
            break
        }
    }
    
    // MARK: - Native Methods
    // 人脸检测
    private func faceAuth(token: String, success: @escaping (Bool) -> Void) {
        let config = FinAuthLiveV5DetectInitConfigItem()
        config.phoneVertical = FinAuthLiveV5DetectPhoneVerticalTypeDisable
        // 设置语言
        config.languageType = FinAuthLiveV5DetectLanguageTypeCh
        config.hostURL = "https://api.yljz.com"
        xLog("活体检测SDK初始化开始（可以加loading动画）")

        FinAuthLiveV5DetectManager.faceLive(withBizToken: token, configInfo: config, extraData: nil, startCallBack: { error, extraOutDict in
            xLog("活体检测SDK初始化结束（可以将loading动画隐藏）")
            if let err = error, err.errorCode != FinAuthLiveV5DetectErrorTypeOK {
                xLog("初始化失败，失败原因：\(err.errorMessage),错误码：\(err.errorCode)")
                success(false)
                return
            }
            xLog("初始化成功，开始进行活体检测。检测页面准备展开")
            
        }, detectVC: controller!) { error, bizTokenStr, extraOutDict in
            xLog("活体检测完成")
            if let err = error, err.errorCode != FinAuthLiveV5DetectErrorTypeOK {
                xLog("检测失败，失败原因：\(err.errorMessage),错误码：\(err.errorCode)")
                success(false)
                return
            }
            xLog("检测成功")
            success(true)
        } dismissCallBack: {
            xLog("活体检测流程结束。检测页面收起。")
        }
    }
    
    /// 显示Toast消息
    private func showToast(message: String) -> Bool {
        DispatchQueue.main.async {
            // 创建一个简单的Toast提示
            let toastLabel = UILabel()
            toastLabel.backgroundColor = UIColor.black.withAlphaComponent(0.6)
            toastLabel.textColor = UIColor.white
            toastLabel.textAlignment = .center
            toastLabel.font = UIFont.systemFont(ofSize: 16.0)
            toastLabel.text = message
            toastLabel.alpha = 1.0
            toastLabel.layer.cornerRadius = 10
            toastLabel.clipsToBounds = true
            
            // 获取当前窗口
            if let windowScene = UIApplication.shared.connectedScenes.first as? UIWindowScene,
               let window = windowScene.windows.first {
                
                let toastContainer = UIView(frame: CGRect(x: 0, y: 0, width: 200, height: 35))
                toastContainer.backgroundColor = UIColor.clear
                toastContainer.addSubview(toastLabel)
                
                toastLabel.frame = CGRect(x: 0, y: 0, width: 200, height: 35)
                toastContainer.center = CGPoint(x: window.frame.size.width / 2, y: window.frame.size.height - 100)
                window.addSubview(toastContainer)
                
                // 3秒后自动消失
                UIView.animate(withDuration: 3.0, delay: 0.1, options: .curveEaseOut, animations: {
                    toastLabel.alpha = 0.0
                }, completion: { _ in
                    toastContainer.removeFromSuperview()
                })
            }
        }
        return true
    }

    // MARK: - Event Sending
    /// 发送事件到Flutter
    func sendEventToFlutter(eventName: String, data: [String: Any]) {
        let eventData: [String: Any] = [
            "eventName": eventName,
            "data": data,
            "timestamp": Int64(Date().timeIntervalSince1970 * 1000)
        ]
        
        eventSink?(eventData)
    }

    /// 调用Flutter方法获取用户信息
    func getUserInfoFromFlutter(completion: @escaping ([String: Any]?) -> Void) {
        methodChannel?.invokeMethod("getUserInfo", arguments: nil) { result in
            if let result = result as? [String: Any] {
                completion(result)
            } else {
                completion(nil)
            }
        }
    }
    
    /// 释放资源
    func dispose() {
        methodChannel?.setMethodCallHandler(nil)
        eventChannel?.setStreamHandler(nil)
        methodChannel = nil
        eventChannel = nil
        eventSink = nil
        
        print("iOS NativeBridge disposed")
    }
}

// MARK: - FlutterEventChannel Stream Handler

extension NativeBridge: FlutterStreamHandler {
    
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        self.eventSink = events
        print("Event channel listener attached")
        return nil
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        self.eventSink = nil
        print("Event channel listener detached")
        return nil
    }
}
extension Dictionary {
    
    func toJsonString() -> String? {
        guard let data = try? JSONSerialization.data(withJSONObject: self,
                                                     options: []) else {
            return nil
        }
        guard let str = String(data: data, encoding: .utf8) else {
            return nil
        }
        return str
     }
    
}
